#ifndef LOCKER_H
#define LOCKER_H

//主要用于请求队列

#include<pthread.h>
#include<exception>
#include<semaphore.h>
using namespace std;
//线程同步机制封装类

//互斥锁类
class locker{

public:
    locker(){
        if(pthread_mutex_init(&m_mutex,NULL)!=0){
             //出错，抛出异常
            throw exception();
        }
    }
    ~locker(){
        pthread_mutex_destroy(&m_mutex);
    }
    //提供上锁的方式
    bool lock();
    //提供解锁的方式
    bool unlock();

    //获取互斥量成员
    pthread_mutex_t* get();
private:
    pthread_mutex_t m_mutex;
};


 //条件变量类（线程池是否还有线程）
 class cond{
public:
    cond(){
        if(pthread_cond_init(&m_cond,NULL)!=0){
            throw exception();
        }
    }
    bool wait(pthread_mutex_t* mutex);

    bool timewait(pthread_mutex_t* mutex,const struct timespec time);
    bool signal();
    bool broadcast();
    ~cond(){
        pthread_cond_destroy(&m_cond);
    }
private:
    pthread_cond_t m_cond;
 };


//信号量类
class sem{
public:
    sem(){
        if(sem_init(&m_sem,0,0)!=0){
            throw exception();
        }
    }
    sem(int num){
        if(sem_init(&m_sem,0,num)!=0){
            throw exception();
        }
    }
    //等待信号量
    bool wait();

    //增加信号量
    bool post();

    ~sem(){
        sem_destroy(&m_sem);
    }

private:
    sem_t m_sem;

};

#endif